package com.inews.base.utils;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.Page;

import com.inews.base.entity.ExtData;
import com.inews.business.entity.PageIndex;


/**
 * ExtData 对象工厂.
 * 
 */
public final class ExtDataUtil {
    
    /**
     * 建立包含单条数据的对象.
     * 
     * @param obj 单个对象
     * 
     * @return the ext data
     */
    public static <T>ExtData<T> genWithSingleData(T t) {
        List<T> data = new ArrayList<T>();
        data.add(t);
        return genWithData(data);
    }


    /**
     * 建立包含正常数据的对象.
     * 
     * @param root the root
     * 
     * @return the ext data
     */
    public static <T>ExtData<T> genWithData(List<T> root) {
        List<T> t_root = root == null ? new ArrayList<T>() : root;
        return getExtData(t_root, t_root.size(), true, null, null);
    }

    /**
     * 根据分页结果生成返回对象。.
     * 
     * @param page the page
     * 
     * @return the ext data
     */
    public static <T>ExtData<T> genWithPagingList(Page<T> page) {
    	PageIndex pageIndex = PageIndex.getPageIndex(page.getNumber() + 1, page.getTotalPages());
        return getExtData(page.getContent(), (int)page.getTotalElements(), true, null, pageIndex);
    }

    
    /**
     * 建立包含业务出错信息的对象.
     * 
     * @param errors the errors
     * 
     * @return the ext data
     */
    public static <T>ExtData<T> genWithErrors(String errors) {
        return getExtData(null, 0, false, errors, null);
    }
    

    
    private static <T>ExtData<T> getExtData(List<T> root, int totalProperty, boolean success, String error, PageIndex pageIndex) {
        ExtData<T> data = new ExtData<T>();
        data.setError(error);
        data.setRoot(root);
        data.setSuccess(success);
        data.setTotalProperty(totalProperty);
        data.setPageIndex(pageIndex);
        return data;
    }
    
}
